package com.baidu.foody.view

import android.animation.ObjectAnimator
import android.content.Context
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import com.baidu.foody.R

class ShimmerAnimationView(context: Context, val layoutId: Int): FrameLayout(context) {
    private var mCoverImageView:ImageView
    init {
        val view = LayoutInflater.from(context).inflate(layoutId,this,false)
        val lp = LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)
        addView(view,lp)

        mCoverImageView = ImageView(context).apply {
            setImageResource(R.drawable.cover)
            scaleType = ImageView.ScaleType.CENTER_INSIDE
        }
        val coverLp = LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT)
        coverLp.marginStart = dp2px(-100)
        addView(mCoverImageView, coverLp)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        startAnimation()
    }

    fun startAnimation(){
        ObjectAnimator.ofFloat(mCoverImageView,"translationX",0f,width.toFloat()+dp2px(100)).apply {
            duration = 800
            repeatCount = ObjectAnimator.INFINITE
            repeatMode = ObjectAnimator.RESTART
            start()
        }
    }

    fun dp2px(dp: Int): Int{
        return (context.resources.displayMetrics.density * dp).toInt()
    }
}